package com.jshan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshan.common.annotation.OperationLog;
import com.jshan.base.entity.SysOperationLog;
import com.jshan.service.SysOperationLogService;
import com.jshan.base.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

@Tag(name = "操作日志接口")
@RestController
@RequestMapping("/log")
@RequiredArgsConstructor
public class SysOperationLogController {

    private final SysOperationLogService operationLogService;

    /**
     * 分页查询操作日志
     *
     * @param pageNum   页码
     * @param pageSize  每页数量
     * @param username  操作人用户名 (可选)
     * @param operation 操作描述 (可选)
     * @return 分页结果
     */
    @Operation(summary = "分页查询操作日志")
    @SaCheckPermission("system:log:list")
    @OperationLog("查询操作日志列表")
    @GetMapping("/page")
    public Result<IPage<SysOperationLog>> getOperationLogPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String operation) {

        IPage<SysOperationLog> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysOperationLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(username != null && !username.isEmpty(), SysOperationLog::getUsername, username);
        queryWrapper.like(operation != null && !operation.isEmpty(), SysOperationLog::getOperation, operation);
        queryWrapper.orderByDesc(SysOperationLog::getCreateTime);

        IPage<SysOperationLog> logPage = operationLogService.page(page, queryWrapper);
        return Result.ok(logPage);
    }

    /**
     * 删除操作日志
     *
     * @param id 日志ID
     * @return 删除结果
     */
    @SaCheckPermission("system:log:delete")
    @OperationLog("删除操作日志")
    @DeleteMapping("/{id}")
    public Result<Void> deleteOperationLog(@PathVariable Long id) {
        operationLogService.removeById(id);
        return Result.ok();
    }
}
